/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3.1-指令详情   3.2-簿记详情  11-组合试算
    info：type=3时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { DATA_ENTRY, FormGroup, codeType } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import moment from 'moment';
import investmentType from '../../../../utils/enumeratedValues/investmentType';
import { calculateFee } from '../../../../utils/commonFunc';

class OrderFormC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //详情
    type: undefined, //当前指令的类型
    SecuritiesCode: undefined, //证券代码val值
    investmentTypeList: [...investmentType], //投资类型下拉
    directionType: '1',
    feeData: {
      //费用自动计算条件
      productId: undefined,
      portfolioid: undefined,
      tradingCode: undefined,
      exchangecode: undefined,
      trademarket: 'jjpt',
      sectype: 'stock',
      sectypeii: 'g',
      orderside: undefined,
      price: undefined,
    },
  };
  componentDidMount() {
    this.props.onRef(this);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}

  //费用自动计算
  changeFeeCalculate = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == '3.1' || this.props.type == '3.2') return; //详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        this.changeFee();
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined, exchangecode: undefined } });
        } else if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode, exchangecode: data.exchangeCode } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue(
                { fee: r },
                this.setState({ fee: r }, () => this.changeFee(r)),
              );
            });
          });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue(
                { fee: r },
                this.setState({ fee: r }, () => this.changeFee(r)),
              );
            });
          });
        }
      }
    }, 100);
  };

  //组合改变
  groupOnChange = (value) => {
    //抛出组合id
    let val;
    if (value) val = value.key;
    this.props.portfolioOnChange(val);
  };
  //证券代码切换
  securitiesCodeChange = (value) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    const { info } = this.props;
    if (info) return; //详情时不进入判断
    this.changeFeeCalculate('tradingCode', value ? value : undefined);
    this.setState({
      SecuritiesCode: value,
    });
    setFieldsValue({
      exchangecode: value ? value.exchangeCode : undefined,
    });
    this.props.tradingcodeOnChange(value);
  };

  //获取当前表单数据 并校验
  getInfo = () => {
    const {
      user: { currentUser },
      money = {},
    } = this.props;
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    let query = undefined;

    validateFields((err, fieldsValue) => {
      if (!err) {
        if (this.state.loadingFee) {
          message.warning('费用还在计算中,请稍后重试!');
          return;
        }
        fieldsValue.totalPrice = parseFloat(fieldsValue.totalPrice.toFixed(2)); //精度丢失问题
        if (fieldsValue.direction == 1) {
          //在下达或确定调用接口之前，根据交易方向，买入时，【金额】与“T+1可用HKD”对比，卖出时，不用对比持仓。
          if (fieldsValue.totalPrice > (money.t1HKD || 0)) {
            message.warning('金额不可大于T+1可用HKD!');
            return;
          }
        }
        query = fieldsValue;
        query.userid = currentUser.userId;
        query.username = currentUser.name;
        query.tradingcode = this.state.SecuritiesCode.tradingCode;
        query.secuabbr = this.state.SecuritiesCode.secuabbr;
        query.fee = 0; //费用隐藏，全部以0计算，计算函数不进行请求，后期需要可放开
        delete query.zqdm;
      }
    });
    return query;
  };
  //重置页面数据 取消
  reset = () => {
    const { form } = this.formGroupThis.props;
    this.props.portfolioOnChange(undefined);
    this.props.tradingcodeOnChange(undefined); //重置组合id和证券代码
    this.setState({
      info: undefined, //详情
      type: undefined, //当前指令的类型
      SecuritiesCode: undefined, //证券代码val值
      directionType: '1',
      feeData: {
        //费用自动计算条件
        productId: undefined,
        portfolioid: undefined,
        tradingCode: undefined,
        exchangecode: undefined,
        trademarket: 'jjpt',
        sectype: 'stock',
        sectypeii: 'g',
        orderside: undefined,
      },
      price: undefined,
      amount: undefined,
    });
    form.resetFields();
  };
  //交易方向变更 投资类型变更买入时默认为FVTPL，卖出时，根据标的，自动回填。
  changeDirect = (e) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    const { info } = this.props;
    if (info) return; //详情不进入
    this.changeFeeCalculate('orderside', e?.value);
    if (!e) {
      setFieldsValue({
        investmentType: 'FVTPL',
      });
      return;
    }
    if (e.value == 1) {
      //买入时默认为FVTPL
      setFieldsValue({
        investmentType: 'FVTPL',
      });
    } else {
      //卖出时，根据标的，自动回填。
      setFieldsValue({
        investmentType: this.props.investmentType,
      });
    }
    this.setState({ directionType: e?.value });
  };

  //form表单渲染
  formRender = () => {
    const { type, info } = this.props;
    let disabled;
    if (type == 1 || type == 2 || type == 11) {
      disabled = false;
    } else {
      disabled = true;
    }
    return (
      <div className={'formOrder'}>
        <FormGroup
          dataSource={[
            {
              disabled: disabled,
              title: ['产品', '组合'],
              type: DATA_ENTRY.PRODUCTGROUPSEP,
              initialValue: info ? [info.productid, info.portfolioid] : undefined,
              authority: 'write',
              multipleGroup: false,
              dataIndex: ['productid', 'portfolioid'],
              rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
              groupOnChange: (e) => {
                this.groupOnChange(e);
                this.props.portfolioCode(e ? e.info.portfolioCode : undefined); //向外抛出组合code
                this.changeFeeCalculate('portfolioid', e?.key);
              },
              productOnChange: (e) => {
                this.changeFeeCalculate('productId', e?.key);
                this.props.productCode(e ? e.info.portfolioCode : undefined); //向外抛出产品code
              },
              allowClear: false,
              exist: 1,
              span: 16,
              controlLabelSpan: 6,
              tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
            },
            {
              dataIndex: 'zqdm',
              title: '证券代码',
              type: DATA_ENTRY.SECURITIESCODE,
              initialValue: info ? `${info.exchangecode}-${info.tradingcode}` : undefined,
              onChange: (e) => this.securitiesCodeChange(e),
              codeType: codeType.gp,
              rules: [{ required: true, message: '请选择证券代码!' }],
              disabled: disabled,
              queryItems: { time: moment(new Date()).format('YYYY-MM-DD'), exchangeCode: '162,166' },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              title: '交易市场',
              dataIndex: 'exchangecode',
              type: DATA_ENTRY.TRADINGMARKET,
              dataType: 1,
              initialValue: info ? info.exchangecode : undefined,
              marketType: ['ggt'],
              rules: [{ required: true, message: '请选择交易市场!' }],
              disabled: true,
              span: 8,
              controlLabelSpan: 6,
              onRef: (ref) => (this.formGroupThis = ref),
            },
            {
              dataIndex: 'investmentType',
              title: '投资类型',
              type: DATA_ENTRY.SELECT,
              disabled: disabled == false ? (this.state.directionType == '2' ? true : false) : disabled,
              initialValue: info ? info.investmentType : 'FVTPL',
              dataSource: investmentType,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'direction', // Form识别的Item ID
              businessType: '19',
              type: DATA_ENTRY.TRADINGDIRECT,
              initialValue: info ? info.direction : '1',
              disabled: disabled,
              allowClear: false,
              rules: [{ required: true, message: '请选择交易方向!' }],
              onChange: this.changeDirect,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'type',
              type: DATA_ENTRY.TRADINGTYPE,
              disabled: true,
              disabled: true,
              initialValue: info ? info.type : '2',
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'price',
              title: type == 1 || type == 3.1 ? '委托价格' : '成交价格',
              unit: 'HKD',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info ? info.price : null,
              splitStyle: true,
              rules: [
                { required: true, message: type == 1 || type == 3.1 ? '请输入委托价格!' : '请输入成交价格!' },
                {
                  validator: this.validatePrice,
                  validateTrigger: 'onBlur',
                },
              ],
              precision: 4,
              disabled: type == 1 ? (this.state.SecuritiesCode ? false : true) : disabled,
              onBlur: (e) => {
                this.changeNum(e, 'price');
              },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'amount',
              title: type == 1 || type == 3.1 ? '委托数量' : '成交数量',
              unit: '股',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info ? info.amount : null,
              splitStyle: true,
              rules: [
                { required: true, message: type == 1 || type == 3.1 ? '请输入委托数量!' : '请输入成交数量!' },
                {
                  validator: this.validateNum,
                  validateTrigger: 'onBlur',
                },
              ],
              disabled: type == 1 ? (this.state.SecuritiesCode ? false : true) : disabled,
              precision: 0,
              onBlur: (e) => {
                this.changeNum(e, 'amount');
              },
              span: 8,
              controlLabelSpan: 6,
            },
            // {
            //   dataIndex: 'fee',
            //   title: '费用',
            //   unit: 'HKD',
            //   type: DATA_ENTRY.INPUTNUMBER,
            //   min: 0,
            //   initialValue: info ? info.fee : undefined,
            //   splitStyle: true,
            //   precision: 2,
            //   disabled: disabled,
            //   onChange: this.changeFee,
            //   span: 8,
            // controlLabelSpan:6,
            // },
            {
              dataIndex: 'totalPrice',
              title: '金额',
              unit: 'HKD',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info ? info.totalPrice : null,
              splitStyle: true,
              rules: [{ required: true, message: '请输入金额!' }],
              precision: 2,
              disabled: true,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'remark',
              type: DATA_ENTRY.INPUT,
              title: '备注',
              disabled: disabled,
              initialValue: info ? info.remark : undefined,
              placeholder: '请输入',
              showTextArea: true,
              autosize: { minRows: 2, maxRows: 2 },
              span: 24,
              controlLabelSpan: 2,
            },
          ]}
          autoLayout={false}
        />
      </div>
    );
  };
  //费用修改
  changeFee = (e) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    this.setState({
      fee: e || 0,
    });
    setFieldsValue({
      totalPrice: parseFloat((this.state.price || 0) * (this.state.amount || 0)) + (e || 0),
    });
  };

  //注意：在这里我只用到了value和callback，没有自定义rule
  validateNum = (rule, value, callback) => {
    if (value === 0) callback('必须大于0');
    if (this.props.type != 1) {
      callback();
    }
    if ((value * 1) % (this.props.lotSize || 0)) {
      //指令   必须是【最小交易单位】的整数倍
      callback('必须是最小交易单位的整数倍');
    } else {
      callback();
    }
  };
  validatePrice = (rule, value, callback) => {
    if (value === 0) callback('必须大于0');
    if (this.props.type != 1) {
      callback();
    }

    if ((value * 1) % (this.props.optionTickSize || 0)) {
      //指令   必须是【最小交易单位】的整数倍
      callback('必须是最小报价单位的整数倍');
    } else {
      callback();
    }
  };

  //修改价格 数量 金额 = 委托价格 * 委托数量 + 费用 后台根据【委托价格】和【委托数量】自动算出费用
  changeNum = (e, type) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    let data = getFieldValue(type);
    this.setState(
      {
        [type]: data,
      },
      () => {
        if (this.state.price !== '' && this.state.price != null) {
          if (this.state.amount !== '' && this.state.amount != null) {
            setFieldsValue({
              totalPrice: parseFloat(this.state.price * this.state.amount) + (this.state.fee || 0), //金额 = 委托价格 * 委托数量 + 费用
            });
            this.changeFeeCalculate('price', parseFloat(this.state.price * this.state.amount) + (this.state.fee || 0));
          } else {
            setFieldsValue({ totalPrice: null });
            this.changeFeeCalculate('price', undefined);
          }
        } else {
          setFieldsValue({ totalPrice: null });
          this.changeFeeCalculate('price', undefined);
        }
      },
    );
  };

  render() {
    return <div className={style.info}>{this.formRender()}</div>;
  }
}
export default connect(({ HKstockM, userM: user, loading }) => ({
  HKstockM,
  user,
  loading,
}))(Form.create()(OrderFormC));
